<template>
  <div>
    <!--	header -->
    <yd-layout v-if="!state">
    <!--	header 
    <mt-header title="OpenId登录" fixed>
      <router-link to="/hello" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
    </mt-header>
    -->
      <yd-cell-group>
        <yd-cell-item>
          <span slot="left">openId：</span>
          <yd-input slot="right" type="text" required v-model="form.code" max="20" placeholder="请输入用户名"></yd-input>
        </yd-cell-item>
      </yd-cell-group>
      <yd-button size="large" type="primary" :disabled="false" shape="circle" @click.native="login">登录</yd-button>
    </yd-layout>
  </div>
</template>
<script>
  import userApi from '@/api/userApi.js'
	import wxCfg from '@wx/WxCfg.js'
	
  export default {
    name: 'login',
    data() {
      return {
        msgUrl: '',
        msgUrlParam: '',
        state: false,
        form: {
          code: ''
        },
        config: wxCfg
      }
    },
    mounted() {
      if (this.isWeiXin()) {
        let url = window.location.href
        let msgUrl = this.$route.query.url
        if (msgUrl && url.indexOf('code') === -1 && (msgUrl.indexOf('check') !== -1 || msgUrl.indexOf('search') !== -1)) {
          this.msgUrlParam = msgUrl.split('#')[1]
        }
        let code = ''
        if (url.indexOf('code') !== -1) {
          if (url.indexOf('state') !== -1) {
            this.msgUrlParam = decodeURIComponent(url.split('state=')[1].split('#')[0])
            code = url.split('&')[0].split('=')[1]
          } else {
            code = url.split('#')[0].split('=')[1]
          }
          userApi.wxLogin({
              code: code
            })
            .then(data => {
              sessionStorage.setItem('token', data.token);
              if (data.index) { // 真正的主页
                if ((this.msgUrlParam.indexOf('check') !== -1) || (this.msgUrlParam.indexOf('search') !== -1)) {
                  this.$router.push(this.msgUrlParam)
                } else {
                  this.$router.push('/hello')
                }
              } else { // 新用户
                this.$router.push('/info')
              }
            })
            .catch(err => {
              // 重新尝试
              this.openAuthPage()
            })

        } else {
          this.openAuthPage()
        }
      }
    },
    methods: {
      isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          this.state = true
          return true;
        } else {
          this.state = false
          return false;
        }
      },
      openAuthPage() {
        let redirectUri = window.encodeURI(window.location.origin)
        let authPageBaseUri = 'https://open.weixin.qq.com/connect/oauth2/authorize'
        let authParams = '?scope=' + this.config.scope + '&agentid=' + this.config.agentid + '&appid=' + this.config.appid + '&redirect_uri=' + redirectUri + '&response_type=' +
          this.config.responseType + '&state=' + this.msgUrlParam + '#wechat_redirect'
        let authUri = authPageBaseUri + authParams
        // window.alert(authUri)
        window.location.href = authUri
      },
      login() {
        this.$dialog.confirm({
          title: '确认登录',
          mes: '确定提交基本信息?',
          opts: () => {
            // 保存逻辑表单逻辑
            userApi.testLogin(this.form)
              .then(data => {
                sessionStorage.setItem('token', data.token)
                this.$router.push('/hello')
              })
              .catch(obj => {
                if (obj.code == 3) {
                  sessionStorage.setItem('token', obj.errMsg)
                  this.$router.push('/info')
                } else {
                  this.$dialog.notify({
                    mes: '提交失败请重试!',
                    timeout: 5000,
                    callback: () => {}
                  })
                }
              })
          }
        })
      }
    }
  }
</script>

<style>

</style>